/**
 * 舆情风险
 */
import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import DataBinder from '@icedesign/data-binder';
import { Grid, Loading, Balloon, Tag, Tab, Button } from "@icedesign/base";
import FoundationSymbol from '@icedesign/foundation-symbol';
// import IceLabel from '@icedesign/label';
// import Masonry from 'react-masonry-component';
import { getRDchart, getKeyWorkCloudChart, getLeftDarChart, getMapChart, getFXPiachart } from '../../echarts-figures.js';
import './OpinionRisk.scss';

const { Row, Col } = Grid;
const Tooltip = Balloon.Tooltip;
const TabPane = Tab.TabPane;

var echarts = require('echarts');
import 'echarts/map/js/china.js';
import 'echarts-wordcloud';

// const wechatNews = [
//   { title: '继无人零售之后，苏宁再度入局无人经济,苏宁最后的下场会是怎么样呢，后续机密接踵而来', sensitive:0, date: '12-03 16:06', sam: 9 },
//   { title: '【一点资讯】2018中国进球奖候选名单公布12月24日即诶揭晓结果，这历史一些新的遵循信息，后续内容将会跟进将于未来的一个多月内揭晓', sensitive:0, date: '12-03 16:06', sam: 9 },
//   { title: '11月百亿级私募关注温氏股份、海康威视等股 4股获百余家机构调研，其中成交最活跃的价格是这些数字', sensitive:0, date: '12-03 16:06', sam: 9 },
//   { title: '一汽轿车与苏宁易购合作布局汽车新零售', sensitive:0, date: '12-03 16:06', sam: 9 },
//   { title: '2019年，养老金还能“上调”多少呢？看完心里有底了，小市值品种具备更高的股性以及活跃度', sensitive:0, date: '12-03 16:06', sam: 9 },
// ]

@DataBinder({
  LineChartData: {
    // url: 'api/getTraditionalScoreChart',
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_info_trend`,
    type: 'get',
    responseFormatter: (responseHandler, res, originResponse) => {
    },
  },

  //关键词接口
  KeyWordChartData: {
    url:`${global.constants.GOLDEYEGETHOST}cattle/opinion_word_cloud`,
    type: 'get',
  },

  LeftDarChartData: {
    url:`${global.constants.GOLDEYEGETHOST}cattle/opinion_media_rate`,
    type: 'get',
  },

  getMapChartData: {
    url:`${global.constants.GOLDEYEGETHOST}cattle/opinion_area_info`,
    type: 'get',
  },

  getGaugeChartData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_emotion_info`,
    type: 'get',
  },

  getHighwordChartData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_positive_word`,
    type: 'get',
  },

  getNegativehwordChartData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_negative_word`,
    type: 'get',
  },

  getSensitiveData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_list`,
    type: 'get'
  },

  getWechatData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_list`,
    type: 'get'
  },

})

export default class OpinionRisk extends Component {
  static displayName = 'OpinionRisk';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      screenWidth: document.body.clientWidth,

      wechatURL: `${global.constants.GOLDEYEGETHOST}cattle/opinion_list?secu_code=${this.GetUrlParam("secu_code")}&originType=5&order=3&similarMerge=1`,
      vBlogURL: `${global.constants.GOLDEYEGETHOST}cattle/opinion_list?secu_code=${this.GetUrlParam("secu_code")}&originType=2&order=3&similarMerge=1`,

      //信息走势图
      LineChartID:'LineChartBox',
      messageLoading:true,
      numbers:{},

      //关键词数据
      KeywordCloudChartID:'KeyWordChartBox',
      keywordLoading:true,
      KeywordConfig:{},

      //情感分布
      GaugeChartID:'GaugeChartBox',
      GaugeLoading:true,
      GaugeConfig:{},

      //媒体来源占比
      LeftDarChartID:'LeftDarchartBox',
      mediaLoading:true,
      DarChartConfig:{},

      //地域分析
      MapChartID:'MapChartBox',
      mapLoading:true,
      MapData:[],
      MapConfig:{},

      //敏感词汇
      Highword:[],
      lowword:[],

      //敏感信息LIST
      sensitiveDataSource:[],
      sen_bol:false,
      sen_Loading:true,
      //微信LIST
      wechatDataSource:[],
      wc_Loading:true,
      //微博LIST
      vblogDataSource:[],
      vb_Loading:true,

      NewListData:{
        timeIndexSelcet:'',
        originType:0,
        similarMerge:0,
        sensitivityType:0,
        order:0
      },
      
      //热点TAB
      tabs: [
        { tab: "微信热点", key: "wechat", content: '暂无热点' },
        { tab: "微博热点", key: "vblog", content:'暂无热点' },
      ],
    };
  }
  componentDidMount() {
     //信息走势图
     this.props.updateBindingData('LineChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("获取折线数据",data);
      if(data.flag){
        this.setState({
          messageLoading:false,
          numbers:getRDchart(
            '信息属性走势图',
            data.data.data_info.dates,
            data.data.data_info.data,
          )
        })
        this.initChart(this.state.numbers,this.state.LineChartID);
      }else{
        console.log("暂无数据")
      }
    });

    // 关键词云数据处理
    this.props.updateBindingData('KeyWordChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("关键词云",data);
      if(data.flag){
        this.setState({
          keywordLoading:false,
          KeywordConfig:getKeyWorkCloudChart(
            '关键词云',
            // keywordcloud,
            data.data.data_info,
          ) 
        })
        this.initKeywordChart(this.state.KeywordConfig,this.state.KeywordCloudChartID);
      }else{
        console.log("关键词云暂无数据")
      }
    });

    //情感分布
    this.props.updateBindingData('getGaugeChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("情感分布饼状图数据",data);
      if(data.flag){
        this.setState({
          GaugeLoading:false,
          GaugeConfig:getFXPiachart(
            '情感分布图',
            data.data.data_list,
          ),
        })
        // console.log("地域分析",this.state.GaugeConfig);
        this.initGaugeChart(this.state.GaugeConfig,this.state.GaugeChartID);
      }else{
        console.log("情感分布暂无数据")
      }
    });

    //地域分析
    this.props.updateBindingData('getMapChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("MapData",data.data.data_list);
      if(data.flag){
        this.setState({
          mapLoading:false,
          MapData:data.data.data_list,
          MapConfig:getMapChart(
            '情感分布图',
            data.data.data_list,
          ) 
        })
        // console.log("地域分析",this.state.MapConfig);
        this.initMapChart(this.state.MapConfig,this.state.MapChartID);
      }else{
        console.log("地域分析暂无数据")
      }
    });

    //媒体来源占比图
    this.props.updateBindingData('LeftDarChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("data",data.data.data_list);
      if(data.flag){
        let xdata = [];
        let ydata = [];
        
        for(let i=0; i<data.data.data_list.length; i++){
          xdata.push(data.data.data_list[i].sources);
          ydata.push(data.data.data_list[i].value);
        }

        this.setState({
          mediaLoading:false,
          DarChartConfig:getLeftDarChart(
            xdata,
            ydata
          ) 
        })
        // console.log("媒体来源占比图",this.state.DarChartConfig);
        this.initChart(this.state.DarChartConfig,this.state.LeftDarChartID);
      }else{
        console.log("媒体来源占比图暂无数据")
      }
    });

    //高频词汇
    this.props.updateBindingData('getHighwordChartData',{
        'params': {
          secu_code:GetUrlParam("secu_code")
        }
      }, (data) => {
        // console.log("Highword",data)
        if(data.flag){
          let cc = []
          for(let i=0;i<data.data.data_info.length;i++){
            cc.push(data.data.data_info[i]);
          }
          this.setState({
            Highword:cc,
          })
        }else{
          console.log("暂无正面词汇")
        }
      });
    this.props.updateBindingData('getNegativehwordChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("Low",data)
      if(data.flag){
        this.setState({
          lowword:data.data.data_info,
        })
      }else{
        console.log("暂无负面词汇")
      }
    });

    //敏感信息提醒
    this.props.updateBindingData('getSensitiveData',{
      'params': {
        secu_code:this.GetUrlParam("secu_code"),
        originType: ["1"],
        sensitivityType: "2",
        order: "3",
        similarMerge: "1"
      }
    }, (data) => {
      if(data.flag){
        this.setState({
          sensitiveDataSource:data.data.data_list
        },()=>{
          this.setState({
            sen_Loading:false
          })
          console.log("获取敏感信息",this.state.sensitiveDataSource);
        })
      }else{
        this.setState({
          sen_Loading:false,
          sen_bol:true
        })
        console.log("worng");
      }
    });

    //获取微信热点
    this.props.updateBindingData('getWechatData',{
      'params': {
        secu_code:this.GetUrlParam("secu_code"),
        originType: "5",
        order: "3",
        similarMerge: "1"
      }
    }, (data) => {
      if(data.flag){
        this.setState({
          wechatDataSource:data.data.data_list
        },()=>{
          this.setState({
            wc_Loading:false
          })
          console.log("获取微信热点",this.state.wechatDataSource);
        })
      }else{
        console.log("worng");
      }
    });

    //获取微博热点
    this.props.updateBindingData('getWechatData',{
      'params': {
        secu_code:this.GetUrlParam("secu_code"),
        originType: "2",
        order: "3",
        similarMerge: "1"
      }
    }, (data) => {
      if(data.flag){
        this.setState({
          vblogDataSource:data.data.data_list
        },()=>{
          this.setState({
            vb_Loading:false
          })
          console.log("获取微博热点",this.state.vblogDataSource);
        })
      }else{
        console.log("worng");
      }
    });

  }

  //屏幕监听
  screenChange() {
    window.addEventListener('resize', this.resize);
  }

  topShow = (item,i) => {
    return(
      <Tag shape="readonly" className="negative-font">{item}</Tag>
    )
  }

  //公共图表
  initChart(config,id,a) {
    let myChart = echarts.getInstanceByDom(document.getElementById(id));
    if( myChart === undefined){
        myChart = echarts.init(document.getElementById(id));
    }
    if(a){
      myChart.setOption(config,true);
    }else{
      myChart.setOption(config);
    }
    window.addEventListener('resize',()=>{
      myChart.resize();
    });
  }

  //地图
  initMapChart(config,id) {
    // console.log(config);
    let mapChart = echarts.getInstanceByDom(document.getElementById(id));
    if( mapChart === undefined){
      mapChart = echarts.init(document.getElementById(id));
    }

    mapChart.setOption(config);

    window.addEventListener('resize',()=>{
      mapChart.resize();
    });
  }

  //敏感分布图
  initGaugeChart(config,id) {
    // console.log(config);
    let GaugeChart = echarts.getInstanceByDom(document.getElementById(id));
    if( GaugeChart === undefined){
      GaugeChart = echarts.init(document.getElementById(id));
    }

    GaugeChart.setOption(config);

    window.addEventListener('resize',()=>{
      GaugeChart.resize();
    });
  }

  //关键词云
  initKeywordChart(config,id) {
    // console.log(config);
    let keywordChart = echarts.getInstanceByDom(document.getElementById(id));
    if( keywordChart === undefined){
      keywordChart = echarts.init(document.getElementById(id));
    }

    keywordChart.setOption(config);

    keywordChart.on('click', function(params) {
        // alert('搜索关键词' + (params.name));
        // window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(params.name));
    });
    
    window.addEventListener('resize',()=>{
      keywordChart.resize();
    });
  }

  resize(){
    this.state = {
      screenWidth: document.body.clientWidth
    };
    console.log("sw",this.state.screenWidth)
  }

  reSizeWidthChange(type){
    if(type == 'fisrt'){
      return this.state.screenWidth*2/3 - 20
    }else if(type == 'second'){
      return this.state.screenWidth*2/3 - 20
    }
  }

  handleChange(key) {
    console.log("change", key);
  }
  
  handleClick(key) {
    console.log("click", key);
  }

  //微信TAB FUNC
  // renderWachet = () => {
  //   return (
  //     <div>
  //     </div>
  //   )
  // }

  onOpen = (ids) => {
    let url = 'https://gdpage.cfbond.com/gdH5/#/'
    window.open(url.split('/#/')[0]+`/#/detail?secu_code=${this.GetUrlParam('secu_code')}&id=${ids}&type=opinion`)
  };

  MoreHot = (timeIndexSelcet,originType,similarMerge,sensitivityType,order) => {
    this.setState({
      NewListData:{
          timeIndexSelcet: timeIndexSelcet,
          originType: originType,
          similarMerge: similarMerge,
          sensitivityType: sensitivityType,
          order: order
        },
      },() => {
        // localStorage.setItem("NewListData",JSON.stringify(this.state.NewListData));
        // window.location.href = `http://192.168.1.190:4447/#/Evaluate/PublicOpinion?originType=${originType}&comblineflg=${comblineflg}&options=${options}&orderBy=${orderBy}&type=1&secu_code=${this.GetUrlParam("secu_code")}`
        // console.log(window.location.href.split('/#/')[0]+ `/#/Evaluate/PublicOpinion?originType=${originType}&comblineflg=${comblineflg}&options=${options}&orderBy=${orderBy}&type=1&secu_code=${this.GetUrlParam("secu_code")}`)
        window.location.href = window.location.href.split('/#/')[0]+ `/#/Evaluate/PublicOpinion?originType=${originType}&similarMerge=${similarMerge}&sensitivityType=${sensitivityType}&order=${order}&type=1&secu_code=${this.GetUrlParam("secu_code")}`
        location.reload(true)
        this.setState({
          activeKey: 1
        })
      })
    // console.log("NewListData",JSON.parse(localStorage.getItem("NewListData")))
  }

  renderMoreContent = () => {
    return (
      <div className="more" onClick={this.MoreHot.bind(this,'24小时','3,4,5,6,7,8,9,10,11,12',1,null,null)}>
        更多<FoundationSymbol type="transfer-right" />
      </div>
    )
      // <Button type="primary" onClick={this.MoreHot.bind(this,'24小时','3,4,5,6,7,8,9,10,11,12',1,null,null)}>
      //   Hello world
      // </Button>
    
  }

  GetUrlParam(paraName)  {
  　var url = document.location.toString();
      // console.log("url",url)
  　var arrObj = url.split("?");
　　　if (arrObj.length > 1) {
　　　　　var arrPara = arrObj[1].split("&");
　　　　　var arr;
　　　　　for (var i = 0; i < arrPara.length; i++) {
　　　　　　　arr = arrPara[i].split("=");
　　　　　　　if (arr != null && arr[0] == paraName) {
　　　　　　　　　return arr[1];
　　　　　　　}
　　　　　}
　　　　　return "";
　　　}
　　　else { return ""; }
  }

  render () {

    const masonryOptions = { transitionDuration: 0 };

    return (
      <div className="opinion-wrapper">
        <IceContainer style={styles.container}>
          <Row type="no-padding">
            {/* <Masonry options={masonryOptions} style={{ width: '100%' }}> */}
              {/* {childElements} */}
              <Col span="8" key="left_big">
                <Row>
                  <div style={{ width: '100%', height: '340px', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <div className="title"><div className="kk"></div>关键词云</div>
                    <div className="left-chart-box">
                      <div id={this.state.KeywordCloudChartID} style={{width: "100%", height: "260px" }}><Loading shape="fusion-reactor" visible={this.state.keywordLoading} color="#fff"></Loading></div>
                    </div>
                  </div>
                </Row>
                <Row>
                  <div style={{ width: '100%', height: '420px', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <div className="title"><div className="kk"></div>全网信息走势图</div>
                    <div className="left-chart-box">
                      <div id={this.state.LineChartID} style={{width: "100%", height: "340px"}}><Loading shape="fusion-reactor" visible={this.state.messageLoading} color="#fff"></Loading></div>
                    </div>
                  </div>
                </Row>
                <Row>
                  <div style={{ width: '100%', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <div className="title"><div className="kk"></div>高频词汇</div>
                    <div style={{minHeight:'320px'}}>
                      <Row wrap type="no-padding">
                        <Col l="12" style={{ paddingLeft:'0', paddingRight:'0' }}>
                          <div className="gpt"><img src="./assetc/zhengmian.png" /><p style={{fontWeight:'bold'}}>正面</p></div>
                          { this.state.Highword.map((item,i) => {
                            return(
                              <div style={{float:'left'}} key={item}>
                                <Tooltip trigger={this.topShow(item,i)} align="t" text={item} className="tooltip-shadow" style={{backgroundColor:'#fff',border:'1px solid #f1f1f1'}}>{item}</Tooltip>
                              </div>
                              // <Tag shape="readonly" key={i} className="positive-font">{item}</Tag>
                            )
                          })}
                        </Col>
                        <Col l="12" style={{ paddingLeft:'0', paddingRight:'0' }}>
                          <div className="gpt"><img src="./assetc/fumian.png" /><p style={{fontWeight:'bold'}}>负面</p></div>
                          <div style={{display:'block',width:'100%'}}>
                          { this.state.lowword.map((item,i) => {
                            return(
                              <div style={{float:'left'}} key={item}>
                                <Tooltip trigger={this.topShow(item,i)} align="t" text={item} className="tooltip-shadow" style={{backgroundColor:'#fff',border:'1px solid #f1f1f1'}}>{item}</Tooltip>
                              </div>
                            )
                          })}
                          </div>
                        </Col>
                      </Row>
                    </div>
                  </div>
                </Row>
              </Col>
              
              <Col span="16" key="right_big">
                <Row>
                  <div style={{ width: '60%', height: '320px', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <div className="title-line">
                      <div className="se-title">
                        <div className="set">
                          <div className="kk"></div>
                          全网敏感信息提醒
                        </div>
                        <div className="more" onClick={this.MoreHot.bind(this,'24小时','3,4,5,6,7,8,9,10,11,12',1,null,null)}>更多<FoundationSymbol type="transfer-right" /></div>
                      </div>
                    </div>
                    <div style={{ height: '240px', overflow: 'scroll' }}>
                      <Loading shape="fusion-reactor" visible={this.state.sen_Loading} color="#fff"></Loading>
                      { this.state.sen_bol && <div style={{ width:'100%',height:'100%',textAlign:'center',verticalAlign:'middle'}}><h4>暂无数据</h4></div>}
                      { this.state.sensitiveDataSource.map((item,i) => {
                        return(
                          <div className="news-box" key={i} onClick={this.onOpen.bind(this,item.id)}>
                            {/* <IceLabel style={{ backgroundColor: '#fde3cf', color: '#f56a00', marginRight:'5px' }}>敏感</IceLabel> */}
                            {item.title}
                            <div style={{ marginTop: '10px', padding:'0' }}>
                              <span className="news-date">{item.publishedMinute}</span>
                            </div>
                          </div>           
                        )
                      })}
                    </div>
                  </div>
                  <div style={{ width: '40%', height: '320px', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <div className="title"><div className="kk"></div>情绪敏感度</div>
                    <div className="left-chart-box">
                      <div id={this.state.GaugeChartID} style={{width: "100%", height: "240px"}}>
                        <Loading shape="fusion-reactor" visible={this.state.GaugeLoading} color="#fff"></Loading>
                      </div>
                    </div>
                  </div>
                </Row>
                <Row>
                  <div style={{ width: '50%', height: '340px', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <div className="title"><div className="kk"></div>媒体来源占比图</div>
                    <div className="left-chart-box">
                      <div id={this.state.LeftDarChartID} style={{width: "100%", height: "260px"}}>
                        <Loading shape="fusion-reactor" visible={this.state.mediaLoading} color="#fff"></Loading>
                      </div>
                    </div>
                  </div>
                  <div style={{ width: '50%', height: '340px', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <div className="title"><div className="kk"></div>地域分析</div>
                    <div>
                      <div id={this.state.MapChartID} style={{ width: "80%", height: "260px",float:'left' }}>
                        <Loading shape="fusion-reactor" visible={this.state.mapLoading} color="#fff"></Loading>
                      </div>
                    </div>
                    <div className="map-table">
                      {this.state.MapData.map((item,i) => {
                        return(
                          <div key={i} className="card-box">{item.name}({item.value})</div>
                        )
                      })}
                    </div>
                  </div>
                </Row>
                <Row>
                  <div style={{ width: '100%', backgroundColor: '#fff', margin: '10px', padding: '10px' }}>
                    <Tab onChange={this.handleChange.bind(this)} tabBarExtraContent={this.renderMoreContent()}>
                      {/* {this.state.tabs.map(item => ( */}
                        <TabPane key="wechat" tab="微信热点" className="tab-content-box" onClick={this.handleClick.bind(this)}>
                          <Loading shape="fusion-reactor" visible={this.state.wc_Loading} color="#fff"></Loading>
                          { this.state.wechatDataSource.map((item,i) => {
                            return(
                              <div className="news-box" key={i} onClick={this.onOpen.bind(this,item.id)}>
                                {/* <IceLabel style={{ backgroundColor: '#fde3cf', color: '#f56a00', marginRight:'5px' }}>敏感</IceLabel> */}
                                {item.title}
                                <div style={{ marginTop: '10px', padding:'0' }}>
                                  <span className="news-date">{item.publishedMinute}</span>
                                </div>
                              </div>           
                            )
                          })}
                        </TabPane>

                        <TabPane key="vblog" tab="微博热点" className="tab-content-box" onClick={this.handleClick.bind(this)}>
                          <Loading shape="fusion-reactor" visible={this.state.vb_Loading} color="#fff"></Loading>
                          { this.state.vblogDataSource.map((item,i) => {
                            return(
                              <div className="news-box" key={i} onClick={this.onOpen.bind(this,item.id)}>
                                {/* <IceLabel style={{ backgroundColor: '#fde3cf', color: '#f56a00', marginRight:'5px' }}>敏感</IceLabel> */}
                                {item.title}
                                <div style={{ marginTop: '10px', padding:'0' }}>
                                  <span className="news-date">{item.publishedMinute}</span>
                                </div>
                              </div>           
                            )
                          })}
                        </TabPane>
                      {/* ))} */}
                    </Tab>
                  </div>
                </Row>
              </Col>

            {/* </Masonry> */}
          </Row>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  container: {
    background: '#F7F8FA',
  },
  itemBody: {
    margin: '10px',
    padding: '10px',
    background: '#fff',
    cursor: 'pointer',
  },
  itemImg: {
    maxWidth: '100%',
  },
  itemTitle: {
    margin: 0,
    padding: '10px 0 0',
    fontSize: '15px',
    textTransform: 'uppercase',
  },
};
